package com.abc.tacos.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import lombok.RequiredArgsConstructor;

/**
 * @author Kar
 * @create 2022-04-20 上午10:42
 */
@Configuration
// @EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig_UserDetails extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/Asuka","/order","design")
                    .access("hasAnyRole('USER','MANAGERS')")
                    // .hasAnyRole("USER", "MANAGERS") 
                .antMatchers("/", "/**")
                    .permitAll() 
            .and()
                .formLogin()
                .loginPage("/login")
                .permitAll()
            .and()
                .logout()
                .logoutSuccessUrl("/")
            .and()
                .csrf()
                .ignoringAntMatchers("/h2-console/**")
            .and()
                .headers()
                .frameOptions()
                .sameOrigin()
        ;
    }

    // 4） 用户自定义存储方式
    // 注入 UserRepositoryUserDetailsService 服务
    // @Autowired
    private final UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth
                // 提供user login服务
                .userDetailsService(userDetailsService)
                // encoder()具有@Bean注解，当调用它时将被拦截，返回容器中它的实例。
                .passwordEncoder(new BCryptPasswordEncoder());
    }
}
